package com.yuzhitong.shapi.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.bytedance.novel.pangolin.NovelSDK;
import com.bytedance.sdk.dp.IDPWidget;
import com.umeng.analytics.MobclickAgent;
import com.yuzhitong.shapi.R;
import a.a.a.MyApplication;
import com.yuzhitong.shapi.base.BaseMvpActivity;
import com.yuzhitong.shapi.bean.UpdateBean;
import com.yuzhitong.shapi.contract.UpdateContract;
import com.yuzhitong.shapi.fragment.HomeFragment;
import com.yuzhitong.shapi.fragment.MovieFragment;
import com.yuzhitong.shapi.fragment.NavigationFragment;
import com.yuzhitong.shapi.fragment.VideoFragment;
import com.yuzhitong.shapi.presenter.UpdatePresenter;
import com.yuzhitong.shapi.util.AppUtil;
import com.yuzhitong.shapi.util.DownloadService;
import com.yuzhitong.shapi.util.GeneralUtil;
import com.yuzhitong.shapi.util.UiUtil;
import com.yuzhitong.shapi.widget.TabLinearLayout;
import com.yuzhitong.shapi.widget.UpdateDialog;

import java.util.Arrays;
import java.util.List;

public class HomeActivity extends BaseMvpActivity<UpdatePresenter> implements UpdateContract.View, View.OnClickListener, DownloadService.OnReceiveMessageListener {

    /**
     * 需要申请的权限数组
     */
    protected String[] needInstallPermissions = {
            // 读取权限
            Manifest.permission.READ_EXTERNAL_STORAGE,
            // 写入权限
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    private final int HOME_POSITION = 0;
    private final int MOVIE_POSITION = 1;
    private final int NAVIGATION_POSITION = 2;
    private final int BOOK_POSITION = 3;
    private final int VIDEO_POSITION = 4;

    private LinearLayout clTab;
    private TabLinearLayout llHomeTab;
    private TabLinearLayout llMovieTab;
    private TabLinearLayout llNavigationTab;
    private TabLinearLayout llBookTab;
    private TabLinearLayout llVideoTab;
    private IDPWidget mIDPWidget;
    private FrameLayout flFragmentBox;


    private List<Fragment> fragments;
    private long blackTime = 0;

    // 选择的 Fragment position
    private int selectPosition;
    private Handler mainHandler;
    private Runnable bookChangePaddingRunnable;

    private UpdateDialog updateDialog;
    private String downloadPath;
    private boolean downloadSuccess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        setDarkStatus();
        mainHandler = new Handler(getMainLooper());
        initView();

        initListener();

        // 初始化乐播
//        LelinkSourceSDK.getInstance()
//                .setBindSdkListener(new IBindSdkListener() {
//                    @Override
//                    public void onBindCallback(boolean b) {
//                        LoggerUtil.e("初始化乐播: " + b);
//                    }
//                })
//                .setSdkInitInfo(getApplicationContext(),"20904","2e1c1c9da548df82cc3a518dd3688863")
//                .bindSdk();
    }

    @Override
    protected void initPresenter() {
        presenter = new UpdatePresenter();
        presenter.attachView(this);
    }

    private void initView() {
        flFragmentBox = findViewById(R.id.fl_fragment_box);
        clTab = findViewById(R.id.cl_tab);
        llHomeTab = findViewById(R.id.ll_home_tab);
        llMovieTab = findViewById(R.id.ll_movie_tab);
        llNavigationTab = findViewById(R.id.ll_navigation_tab);
        llBookTab = findViewById(R.id.ll_book_tab);
        llVideoTab = findViewById(R.id.ll_video_tab);

        // 小说视频
        if (MyApplication.isOpenAdContent()) {
//            llBookTab.setVisibility(View.VISIBLE);
            llVideoTab.setVisibility(View.VISIBLE);
        } else {
            llBookTab.setVisibility(View.GONE);
            llVideoTab.setVisibility(View.GONE);
        }

        // 影视
        if (MyApplication.isOpenMovie()) {
            llMovieTab.setVisibility(View.VISIBLE);
        } else {
            llMovieTab.setVisibility(View.GONE);
        }
//        llMovieTab.setVisibility(View.GONE);

        llHomeTab.setImageUrl(R.mipmap.icon_tab_home);
        llMovieTab.setImageUrl(R.mipmap.icon_tab_movie);
        llNavigationTab.setImageUrl(R.mipmap.icon_tab_navigation);
        llBookTab.setImageUrl(R.mipmap.icon_tab_book);
        llVideoTab.setImageUrl(R.mipmap.icon_tab_video);

        llHomeTab.setText(R.string.tab_home);
        llMovieTab.setText(R.string.tab_movie);
        llNavigationTab.setText(R.string.tab_navigation);
        llBookTab.setText(R.string.tab_book);
        llVideoTab.setText(R.string.tab_video);

        fragments = Arrays.asList(null, null, null, null, null);
        selectPosition = HOME_POSITION;
        showFragmentByIndex(HOME_POSITION);

        presenter.getUpdateLog();
        presenter.getCategory();
    }

    private void initListener() {
        llHomeTab.setOnClickListener(this);
        llMovieTab.setOnClickListener(this);
        llNavigationTab.setOnClickListener(this);
        llBookTab.setOnClickListener(this);
        llVideoTab.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIDPWidget != null && mIDPWidget.getFragment() != null) {
            mIDPWidget.getFragment().onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mIDPWidget != null && mIDPWidget.getFragment() != null) {
            mIDPWidget.getFragment().onPause();
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - blackTime > 2000) {
            blackTime = System.currentTimeMillis();
            Toast.makeText(this, getResources().getString(R.string.back_hint), Toast.LENGTH_SHORT).show();
            return;
        }
        MobclickAgent.onKillProcess(getApplicationContext());
        super.onBackPressed();
    }


    private void select(int type) {
        switch (type) {
            case HOME_POSITION:
                llHomeTab.setImageUrl(R.mipmap.icon_tab_home_checked);
                llHomeTab.setTextColor(getResources().getColor(R.color.tab_selected));
                break;
            case MOVIE_POSITION:
                llMovieTab.setImageUrl(R.mipmap.icon_tab_movie_checked);
                llMovieTab.setTextColor(getResources().getColor(R.color.tab_selected));
                break;
            case NAVIGATION_POSITION:
                llNavigationTab.setImageUrl(R.mipmap.icon_tab_navigation_checked);
                llNavigationTab.setTextColor(getResources().getColor(R.color.tab_selected));
                break;
            case BOOK_POSITION:
                llBookTab.setImageUrl(R.mipmap.icon_tab_book_checked);
                llBookTab.setTextColor(getResources().getColor(R.color.tab_selected));
                break;
            case VIDEO_POSITION:
                llVideoTab.setImageUrl(R.mipmap.icon_tab_video_checked);
                llVideoTab.setTextColor(getResources().getColor(R.color.tab_selected));
                break;
        }
    }

    private void unSelectAll() {
        llNavigationTab.setImageUrl(R.mipmap.icon_tab_navigation);
        llMovieTab.setImageUrl(R.mipmap.icon_tab_movie);
        llBookTab.setImageUrl(R.mipmap.icon_tab_book);
        llVideoTab.setImageUrl(R.mipmap.icon_tab_video);
        llHomeTab.setImageUrl(R.mipmap.icon_tab_home);
    }

    private void setTabTextColorAll(int color) {
        llNavigationTab.setTextColor(color);
        llMovieTab.setTextColor(color);
        llBookTab.setTextColor(color);
        llVideoTab.setTextColor(color);
        llHomeTab.setTextColor(color);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        unSelectAll();
        if (id == R.id.ll_navigation_tab) {
            select(NAVIGATION_POSITION);
            showFragmentByIndex(NAVIGATION_POSITION);
        } else if (id == R.id.ll_movie_tab) {
            select(MOVIE_POSITION);
            showFragmentByIndex(MOVIE_POSITION);
        } else if (id == R.id.ll_book_tab) {
            select(BOOK_POSITION);
            showFragmentByIndex(BOOK_POSITION);
        } else if (id == R.id.ll_video_tab) {
            select(VIDEO_POSITION);
            showFragmentByIndex(VIDEO_POSITION);
        } else {
            select(HOME_POSITION);
            showFragmentByIndex(HOME_POSITION);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    public void showFragmentByIndex(int index) {
        unSelectAll();
        refreshBar(index);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (fragments.get(index) == null) {
            switch (index) {
                case HOME_POSITION:
                default:
                    llHomeTab.setTextColor(getResources().getColor(R.color.tab_selected));
                    fragments.set(HOME_POSITION, HomeFragment.newInstance());
                    fragmentTransaction.add(R.id.fl_fragment_box, fragments.get(HOME_POSITION));
                    break;
                case MOVIE_POSITION:
                    llMovieTab.setTextColor(getResources().getColor(R.color.tab_selected));
                    fragments.set(MOVIE_POSITION, MovieFragment.newInstance());
                    fragmentTransaction.add(R.id.fl_fragment_box, fragments.get(MOVIE_POSITION));
                    break;
                case NAVIGATION_POSITION:
                    llNavigationTab.setTextColor(getResources().getColor(R.color.tab_selected));
                    fragments.set(NAVIGATION_POSITION, NavigationFragment.newInstance());
                    fragmentTransaction.add(R.id.fl_fragment_box, fragments.get(NAVIGATION_POSITION));
                    break;
                case BOOK_POSITION:
                    llBookTab.setTextColor(getResources().getColor(R.color.tab_selected));
                    Fragment fragment = NovelSDK.INSTANCE.getNovelFragment();

                    // 设置小说页面头部padding
                    mainHandler.postDelayed(bookChangePaddingRunnable = new Runnable() {
                        @Override
                        public void run() {
                            View rootView = fragment.getView();
                            if (rootView == null) {
                                mainHandler.postDelayed(bookChangePaddingRunnable, 100);
                                return;
                            }
                            rootView.setPadding(
                                    rootView.getPaddingLeft(),
                                    rootView.getPaddingTop() + getStatusBarHeight(),
                                    rootView.getPaddingRight(),
                                    rootView.getPaddingBottom()
                            );
                        }
                    }, 100);
                    fragments.set(BOOK_POSITION, fragment);
                    fragmentTransaction.add(R.id.fl_fragment_box, fragments.get(BOOK_POSITION));
                    break;
                case VIDEO_POSITION:
                    llVideoTab.setTextColor(getResources().getColor(R.color.tab_selected));
//                    // 视频配置
//                    DPWidgetDrawParams params = DPWidgetDrawParams.obtain();
//                    params.mIsHideClose = true;
//
//                    LoggerUtil.i("状态栏高度:" + UiUtil.getStatusBarHeightDp(HomeActivity.this));
//                    params.titleTopMargin(UiUtil.getStatusBarHeightDp(HomeActivity.this));
//                    params.drawChannelType(DPWidgetDrawParams.DRAW_CHANNEL_TYPE_RECOMMEND);
//                    params.hideChannelName(true);
//                    params.drawContentType(DPWidgetDrawParams.DRAW_CONTENT_TYPE_ALL);
//                    params.hideFollow(true);
//                    params.listener(new IDPBannerListener() {
//                        @Override
//                        public void onDPVideoPause(Map<String, Object> map) {
//                            super.onDPVideoPause(map);
//                            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//                        }
//
//                        @Override
//                        public void onDPVideoPlay(Map<String, Object> map) {
//                            super.onDPVideoPlay(map);
//                            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//                        }
//                    });
//                    mIDPWidget = DPSdk.factory().createDraw(params);
//                    fragments.set(VIDEO_POSITION, mIDPWidget.getFragment());
                    fragments.set(VIDEO_POSITION, VideoFragment.newInstance());
                    fragmentTransaction.add(R.id.fl_fragment_box, fragments.get(VIDEO_POSITION));
                    break;
            }
        }
        for (int i = 0; i < fragments.size(); i++) {
            if (i == index) {
                fragmentTransaction.show(fragments.get(i));
                continue;
            }
            if (fragments.get(i) != null) {
                fragmentTransaction.hide(fragments.get(i));
            }
        }
        fragmentTransaction.commit();
    }

    /**
     * 修改Tab和状态栏
     *
     * @param index 页面 position
     */
    private void refreshBar(int index) {
        //        if (index == BOOK_POSITION) {
        //            flFragmentBox.setPadding(
        //                    flFragmentBox.getPaddingLeft(),
        //                    getStatusBarHeight(),
        //                    flFragmentBox.getPaddingRight(),
        //                    flFragmentBox.getPaddingBottom()
        //            );
        //        } else {
        //            flFragmentBox.setPadding(
        //                    flFragmentBox.getPaddingLeft(),
        //                    0,
        //                    flFragmentBox.getPaddingRight(),
        //                    flFragmentBox.getPaddingBottom()
        //            );
        //        }
        if (index == VIDEO_POSITION) {
            clTab.setBackgroundColor(0xFF000000);
            if (selectPosition != VIDEO_POSITION) {
                AppUtil.backgroundAnimation(clTab, 0xFFFFFFFF, 0xFF000000, 200);
            }
            getWindow().setNavigationBarColor(0xFF000000);
            getWindow().setBackgroundDrawableResource(R.color.black);
        } else {
            clTab.setBackgroundColor(0xFFFFFFFF);
            if (selectPosition == VIDEO_POSITION) {
                AppUtil.backgroundAnimation(clTab, 0xFF000000, 0xFFFFFFFF, 200);
            }
            getWindow().setNavigationBarColor(0xFFFFFFFF);
            getWindow().setBackgroundDrawable(null);
        }

        if (index == VIDEO_POSITION || index == MOVIE_POSITION) {
            UiUtil.setStatusDark(this, false);
        } else {
            UiUtil.setStatusDark(this, true);
        }
        setTabTextColorAll(getResources().getColor(R.color.tab_un_selected));
        selectPosition = index;
        select(index);
    }

    @Override
    public void showUpdateDialog(UpdateBean bean) {
        updateDialog = new UpdateDialog(this, bean);

        updateDialog.setOnClickBtnListener(new UpdateDialog.OnClickBtnListener() {
            @Override
            public void onDismiss() {

            }

            @Override
            public void onConfirm(UpdateBean updateBean) {
                if (permissionInstall()) {
                    if (downloadSuccess) {
                        Intent installAppIntent = GeneralUtil.getInstallAppIntent(HomeActivity.this, downloadPath);
                        startActivity(installAppIntent);
                        return;
                    }
                    DownloadService.addOnReceiveMessageListener(HomeActivity.this);
                    Intent intent = new Intent(HomeActivity.this, DownloadService.class);
                    intent.putExtra("downloadUrl", updateBean.getDownloadAddress());
                    startService(intent);
                } else {
                    ActivityCompat.requestPermissions(HomeActivity.this, needInstallPermissions, REQUEST_PERMISSION_CODE);
                }
            }
        });
        updateDialog.show();
    }


    @Override
    public void startDownload(String goodsId) {
        updateDialog.updateProgress(0);
    }

    @Override
    public void setDownloadProgress(int progress) {
        if (progress >= 100) {
            downloadSuccess = true;
        } else {
            downloadSuccess = false;
        }
        updateDialog.updateProgress(progress);
    }

    @Override
    public void endDownload(String downloadPath) {
        if (downloadSuccess) {
            this.downloadPath = downloadPath;
            updateDialog.updateProgress(100);
            GeneralUtil.getInstallAppIntent(this, downloadPath);
        } else {
            error("未下载完成");
        }
    }

    @Override
    public void error(String msg) {
        downloadSuccess = false;
        updateDialog.downloadError();
    }


    /**
     * 是否授权 必要权限
     */
    private boolean permissionInstall() {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                && PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
}